package chapter01;

/**
 * 两数相加
 */
public class AddTwoNumbers {

    class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    /**
     * 链表相加，从个位向高位依次进行计算，注意低位向高位的进位
     * 两个链表长度不一定相等，注意其中某个链表空指针异常
     * 本题使用div保存进位值，temp保存本次位上相加结果值，为了方便添加头节点
     */
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(0);
        ListNode cur = head;
        int div = 0, temp;
        while (l1 != null || l2 != null) {
            temp = div;
            if (l1 != null) {
                temp = temp + l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                temp = temp + l2.val;
                l2 = l2.next;
            }
            ListNode node = new ListNode(temp % 10);
            cur.next = node;
            cur = cur.next;
            div = temp / 10;
        }
        if (div != 0) {
            ListNode node = new ListNode(div);
            cur.next = node;
        }
        return head.next;
    }
}
